import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:rembercount/controller/countController.dart';
import 'package:rembercount/controller/authLoginController.dart';
import 'package:rembercount/controller/categoryController.dart';
import 'package:rembercount/controller/themeController.dart';
import 'package:rembercount/pages/homepage.dart';
import 'package:rembercount/pages/main_page.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:intl/intl.dart';

class RecordPage extends StatefulWidget {
  const RecordPage({super.key});

  @override
  State<RecordPage> createState() => _RecordPageState();
}

class _RecordPageState extends State<RecordPage> {
  final CountController countController = Get.find<CountController>();
  final Authlogincontroller authlogincontroller =
      Get.find<Authlogincontroller>();
  final CategoryController categoryController = Get.find<CategoryController>();
  final ThemeController themeController = Get.find<ThemeController>();

  String selectedCategory = '饮食';
  String selectedType = '支出';
  // Homepage homepage=Get.find<Homepage>();
  final TextEditingController amountController = TextEditingController();
  final TextEditingController noteController = TextEditingController();
  final TextEditingController newCategoryController = TextEditingController();
  final FocusNode amountFocusNode = FocusNode();
  IconData selectedIcon = Icons.add;
  // 分期选项
  // int? selectedInstallment; // 选中的分期数
  final List<int> installmentOptions = [3, 6, 12, 24];
  RxDouble oneStagesAmount = RxDouble(0);
  Rx<DateTime> firstPaymentDate = DateTime.now().obs;
  // 添加交易时间选择
  Rx<DateTime> transactionDate = DateTime.now().obs;
    void changeAmount() async {
    var res = await countController.getAssetType();
    List<Map<String, dynamic>> list = List<Map<String, dynamic>>.from(res);

    // 展示自定义actionSheet
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (BuildContext context) {
        return Container(
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 标题栏
              Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  border: Border(
                    bottom: BorderSide(color: Colors.grey[300]!),
                  ),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      "选择账户",
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: themeController.themeColor,
                      ),
                    ),
                    IconButton(
                      onPressed: () => Navigator.pop(context),
                      icon: const Icon(Icons.close),
                    ),
                  ],
                ),
              ),
              // 账户列表
              Container(
                constraints: BoxConstraints(
                  maxHeight: MediaQuery.of(context).size.height * 0.4,
                ),
                child: ListView.builder(
                  shrinkWrap: true,
                  itemCount: list.length,
                  itemBuilder: (context, index) {
                    
                    final element = list[index];
                    return ListTile(
                      leading: Container(
                        padding: const EdgeInsets.all(8),
                        decoration: BoxDecoration(
                          color: themeController.themeColor.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: Icon(
                          _getIconFromString(element['icon']),
                          color: themeController.themeColor,
                          size: 24,
                        ),
                      ),
                      title: Text(
                        element['label'],
                        style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      onTap: () {
                        countController.walletAccount.text = element['label'];
                        Navigator.pop(context);
                        _saveRecord();
                      },
                    );
                  },
                ),
              ),
              // 取消按钮
              Container(
                width: double.infinity,
                padding: const EdgeInsets.all(16),
                child: ElevatedButton(
                  onPressed: () => Navigator.pop(context),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.grey[200],
                    foregroundColor: Colors.grey[700],
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  child: const Text(
                    "取消选择",
                    style: TextStyle(fontSize: 16),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  IconData _getIconFromString(String iconName) {
    switch (iconName) {
      case 'wallet':
        return Icons.account_balance_wallet;
      case 'bank':
        return Icons.account_balance;
      case 'saving':
        return Icons.savings;
      case 'credit':
        return Icons.credit_card;
      case 'cash':
        return Icons.money;
      default:
        return Icons.account_balance_wallet;
    }
  }

  @override
  void initState() {
    super.initState();
    if (categoryController.categories.isNotEmpty) {
      selectedCategory = categoryController.categories[0]['name'];
    }
    var record = Get.arguments;
    if (Get.arguments != null) {
      // print("record:${record['record']}");
      var index = record['index'];
      amountController.text = record['record']['amount'].toString();
      selectedCategory = record['record']['category'];
      selectedType = record['record']['countType'] == 'zhi' ? '支出' : '收入';
      // 设置交易时间
      if (record['record']['date'] != null) {
        transactionDate.value = DateTime.parse(record['record']['date']);
      }
    }
    // 添加延迟以确保在页面完全加载后聚焦
    Future.delayed(Duration.zero, () {
      amountFocusNode.requestFocus();
    });
  }

  @override
  void dispose() {
    amountFocusNode.dispose();
    super.dispose();
  }

  String selectedTypeCheck(String selectedType) {
    return selectedType == '支出' ? 'zhi' : 'shou';
  }

  Future<void> _saveRecord() async {
    if (amountController.text.isEmpty) {
      Get.snackbar(
        '提示',
        '请输入金额',
        backgroundColor: Colors.red.withOpacity(0.1),
        colorText: Colors.red,
        duration: const Duration(seconds: 2),
      );
      return;
    }

    // 清理金额输入
    String cleanAmount = amountController.text.replaceAll(
      RegExp(r'[^\d.]'),
      '',
    );
    if (cleanAmount.split('.').length > 2) {
      cleanAmount =
          cleanAmount.split('.')[0] +
          '.' +
          cleanAmount.split('.').sublist(1).join('');
    }
    double? amount = double.tryParse(cleanAmount);

    if (amount == null || amount <= 0) {
      Get.snackbar(
        '提示',
        '请输入有效的金额',
        backgroundColor: Colors.red.withOpacity(0.1),
        colorText: Colors.red,
        duration: const Duration(seconds: 2),
      );
      return;
    }

    String validationMsg = countController.check(cleanAmount, selectedCategory);

    if (validationMsg.isNotEmpty) {
      Get.snackbar(
        '提示',
        validationMsg,
        backgroundColor: Colors.red.withOpacity(0.1),
        colorText: Colors.red,
        duration: const Duration(seconds: 2),
      );
      return;
    }

    try {
      countController.categoryController.text = selectedCategory;
      countController.noteController.text = noteController.text;
      countController.amountController.text = cleanAmount;
      countController.dateController.text = transactionDate.value
          .toString()
          .substring(0, 19);
      countController.countType.value = selectedTypeCheck(selectedType);

      // 只有在选择了分期时才设置分期相关数据
      if (countController.stages.value != null) {
        countController.firstPaymentDate.value = firstPaymentDate.value;
      }

      var res;
      var record = Get.arguments;
      if (Get.arguments != null) {
        record['record']['amount'] = cleanAmount;
        record['record']['category'] = selectedCategory;
        record['record']['countType'] = selectedTypeCheck(selectedType);
        record['record']['stages'] = countController.stages.value;
        record['record']['date'] = transactionDate.value.toIso8601String();
        if (countController.stages.value != null) {
          record['record']['firstPaymentDate'] =
              firstPaymentDate.value.toIso8601String();
        }
        res = await countController.edit(record['record']);
      } else {
        res = await countController.saveCount();
      }

      if (res['code'] == 200) {
        Get.snackbar(
          '成功',
          res['msg'],
          backgroundColor: themeController.themeColor.withOpacity(0.1),
          colorText: themeController.themeColor,
          duration: const Duration(seconds: 2),
        );

        amountController.clear();
        noteController.clear();
        setState(() {
          selectedCategory = categoryController.categories[0]['name'];
          selectedType = '支出';
        });
        print('Save response: $res');
        Get.offAll(() => MainPage());
      } else {
        Get.snackbar(
          '失败',
          res['msg'] ?? '记账失败',
          backgroundColor: Colors.red.withOpacity(0.1),
          colorText: Colors.red,
          duration: const Duration(seconds: 2),
        );
      }
    } catch (e) {
      print('Error saving record: $e');
      Get.snackbar(
        '错误',
        '保存失败: $e',
        backgroundColor: Colors.red.withOpacity(0.1),
        colorText: Colors.red,
        duration: const Duration(seconds: 2),
      );
    }
  }

  void _showAddCategoryDialog() {
    newCategoryController.clear();
    selectedIcon = Icons.add;

    showDialog(
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return AlertDialog(
              title: const Text('添加分类'),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  TextField(
                    controller: newCategoryController,
                    decoration: InputDecoration(
                      labelText: '分类名称',
                      border: OutlineInputBorder(),
                    ),
                  ),
                  const SizedBox(height: 16),
                  Wrap(
                    spacing: 8,
                    runSpacing: 8,
                    children:
                        CategoryController.availableIcons.entries.map((entry) {
                          return _buildIconButton(entry.value, setState);
                        }).toList(),
                  ),
                ],
              ),
              actions: [
                TextButton(
                  onPressed: () => Navigator.pop(context),
                  child: Text(
                    '取消',
                    style: TextStyle(color: themeController.themeColor),
                  ),
                ),
                TextButton(
                  onPressed: () async {
                    if (newCategoryController.text.isEmpty) {
                      Get.snackbar(
                        '提示',
                        '请输入分类名称',
                        backgroundColor: Colors.red.withOpacity(0.1),
                        colorText: Colors.red,
                        duration: const Duration(seconds: 2),
                      );
                      return;
                    }

                    await categoryController.addCategory(
                      newCategoryController.text,
                      selectedIcon,
                    );

                    Navigator.pop(context);
                    setState(() {
                      selectedCategory = newCategoryController.text;
                    });
                  },
                  child: Text(
                    '添加',
                    style: TextStyle(color: themeController.themeColor),
                  ),
                ),
              ],
            );
          },
        );
      },
    );
  }

  RxDouble? oneStagesAmountCoupted() {
    if (countController.stages.value != null &&
        amountController.text.isNotEmpty) {
      try {
        // 移除所有非数字字符（除了小数点）
        String cleanAmount = amountController.text.replaceAll(
          RegExp(r'[^\d.]'),
          '',
        );
        // 确保只有一个小数点
        if (cleanAmount.split('.').length > 2) {
          cleanAmount =
              cleanAmount.split('.')[0] +
              '.' +
              cleanAmount.split('.').sublist(1).join('');
        }
        double amount = double.tryParse(cleanAmount) ?? 0;
        if (amount > 0 && countController.stages.value! > 0) {
          oneStagesAmount.value = amount / countController.stages.value!;
        } else {
          oneStagesAmount.value = 0;
        }
      } catch (e) {
        print('Error calculating installment amount: $e');
        oneStagesAmount.value = 0;
      }
    } else {
      oneStagesAmount.value = 0;
    }
  }

  Widget _buildIconButton(IconData icon, StateSetter setState) {
    final isSelected = selectedIcon == icon;
    return InkWell(
      onTap: () {
        setState(() {
          selectedIcon = icon;
        });
      },
      child: Container(
        padding: const EdgeInsets.all(8),
        decoration: BoxDecoration(
          color:
              isSelected
                  ? themeController.themeColor.withOpacity(0.1)
                  : Colors.grey[50],
          shape: BoxShape.circle,
          border: Border.all(
            color: isSelected ? themeController.themeColor : Colors.transparent,
            width: 2,
          ),
        ),
        child: Icon(
          icon,
          color: isSelected ? themeController.themeColor : Colors.grey,
          size: 24,
        ),
      ),
    );
  }

  void _showRecordDetails(Map<String, dynamic> record) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder:
          (context) => Container(
            height: MediaQuery.of(context).size.height * 0.7,
            decoration: const BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
            ),
            child: Column(
              children: [
                Container(
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: const BorderRadius.vertical(
                      top: Radius.circular(20),
                    ),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.1),
                        blurRadius: 10,
                        offset: const Offset(0, -2),
                      ),
                    ],
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        '交易详情',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                          color: themeController.themeColor,
                        ),
                      ),
                      IconButton(
                        onPressed: () => Navigator.pop(context),
                        icon: const Icon(Icons.close),
                      ),
                    ],
                  ),
                ),
                Expanded(
                  child: SingleChildScrollView(
                    padding: const EdgeInsets.all(16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        _buildDetailItem('分类', record['category']),
                        _buildDetailItem('金额', '¥${record['amount']}'),
                        _buildDetailItem('每日回本金额', '¥${record['reFund']}'),

                        _buildDetailItem('日期', record['date']),
                        _buildDetailItem(
                          '类型',
                          record['countType'] == 'zhi' ? '支出' : '收入',
                        ),
                        if (record['stages'] != null) ...[
                          _buildDetailItem('分期数', '${record['stages']}期'),
                          const SizedBox(height: 16),
                          const Text(
                            '分期详情',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 8),
                          if (record['stagesList'] != null)
                            ...record['stagesList']
                                .map<Widget>(
                                  (stage) => Container(
                                    margin: const EdgeInsets.only(bottom: 8),
                                    padding: const EdgeInsets.all(12),
                                    decoration: BoxDecoration(
                                      color: Colors.grey[50],
                                      borderRadius: BorderRadius.circular(8),
                                    ),
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(
                                          stage['stage'],
                                          style: const TextStyle(
                                            fontSize: 14,
                                            fontWeight: FontWeight.w500,
                                          ),
                                        ),
                                        Text(
                                          '¥${stage['amount']}',
                                          style: TextStyle(
                                            fontSize: 14,
                                            fontWeight: FontWeight.bold,
                                            color: themeController.themeColor,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                )
                                .toList(),
                        ],
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
    );
  }

  Widget _buildDetailItem(String label, String value) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 16),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(label, style: const TextStyle(fontSize: 16, color: Colors.grey)),
          Text(
            value,
            style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).unfocus();
      },
      child: Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          backgroundColor: Colors.white,
          elevation: 0,
          title: Text(
            '记一笔',
            style: TextStyle(
              color: themeController.themeColor,
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
          ),
          centerTitle: true,
        ),
        body: Stack(
          children: [
            SingleChildScrollView(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 1. 支出/收入类型切换
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        _buildTypeButton('支出', selectedType == '支出'),
                        const SizedBox(width: 20),
                        _buildTypeButton('收入', selectedType == '收入'),
                      ],
                    ),
                    const SizedBox(height: 24),

                    // 2. 金额输入框
                    Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 16,
                        vertical: 8,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.grey[50],
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: TextField(
                        controller: amountController,
                        focusNode: amountFocusNode,
                        onSubmitted: (_) {
                          amountFocusNode.unfocus();
                        },
                        onChanged: (value) {
                          oneStagesAmountCoupted();
                        },
                        keyboardType: const TextInputType.numberWithOptions(
                          decimal: true,
                        ),
                        style: TextStyle(
                          fontSize: 32,
                          fontWeight: FontWeight.bold,
                          color: themeController.themeColor,
                        ),
                        decoration: InputDecoration(
                          hintText: '0.00',
                          hintStyle: const TextStyle(color: Colors.grey),
                          prefixText: '¥ ',
                          prefixStyle: TextStyle(
                            fontSize: 32,
                            fontWeight: FontWeight.bold,
                            color: themeController.themeColor,
                          ),
                          border: InputBorder.none,
                        ),
                      ),
                    ),
                    const SizedBox(height: 16),

                    // 添加交易时间选择
                    InkWell(
                      onTap: _selectTransactionDate,
                      child: Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 16,
                          vertical: 12,
                        ),
                        decoration: BoxDecoration(
                          color: Colors.grey[50],
                          borderRadius: BorderRadius.circular(12),
                          border: Border.all(color: Colors.grey[300]!),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              '交易时间：${DateFormat('yyyy-MM-dd HH:mm').format(transactionDate.value)}',
                              style: const TextStyle(fontSize: 16),
                            ),
                            Icon(
                              Icons.calendar_today,
                              size: 20,
                              color: themeController.themeColor,
                            ),
                          ],
                        ),
                      ),
                    ),
                    const SizedBox(height: 16),

                    // 3. 分期选择
                    SingleChildScrollView(
                      scrollDirection: Axis.horizontal,
                      child: Row(
                        children: [
                          const Text(
                            '分期：',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 4),
                            child: ChoiceChip(
                              label: const Text('不分期'),
                              selected: countController.stages.value == null,
                              selectedColor: themeController.themeColor,
                              onSelected: (selected) {
                                setState(() {
                                  countController.stages.value = null;
                                  oneStagesAmount.value = 0;
                                });
                              },
                              labelStyle: TextStyle(
                                color:
                                    countController.stages.value == null
                                        ? Colors.white
                                        : Colors.black87,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                          ...installmentOptions.map(
                            (opt) => Padding(
                              padding: const EdgeInsets.symmetric(
                                horizontal: 4,
                              ),
                              child: ChoiceChip(
                                label: Text('$opt期'),
                                selected: countController.stages.value == opt,
                                selectedColor: themeController.themeColor,
                                onSelected: (selected) {
                                  setState(() {
                                    countController.stages.value =
                                        selected ? opt : null;
                                    oneStagesAmountCoupted();
                                  });
                                },
                                labelStyle: TextStyle(
                                  color:
                                      countController.stages.value == opt
                                          ? Colors.white
                                          : Colors.black87,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    reFund(),
                    const SizedBox(height: 16),
                    Obx(
                      () =>
                          countController.stages.value != null
                              ? Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    '单期金额：${(oneStagesAmount.value).toStringAsFixed(2)}',
                                    style: TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                  const SizedBox(height: 8),
                                  InkWell(
                                    onTap: _selectFirstPaymentDate,
                                    child: Container(
                                      padding: const EdgeInsets.symmetric(
                                        horizontal: 16,
                                        vertical: 8,
                                      ),
                                      decoration: BoxDecoration(
                                        color: Colors.grey[50],
                                        borderRadius: BorderRadius.circular(8),
                                        border: Border.all(
                                          color: Colors.grey[300]!,
                                        ),
                                      ),
                                      child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text(
                                            '首次还款日期：${DateFormat('yyyy-MM-dd').format(firstPaymentDate.value)}',
                                            style: const TextStyle(
                                              fontSize: 14,
                                            ),
                                          ),
                                          Icon(
                                            Icons.calendar_today,
                                            size: 16,
                                            color: themeController.themeColor,
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                  const SizedBox(height: 16),
                                  const Text(
                                    '分期还款计划',
                                    style: TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                  const SizedBox(height: 8),
                                  ...countController
                                      .calculateInstallmentDates()
                                      .map(
                                        (installment) => Container(
                                          margin: const EdgeInsets.only(
                                            bottom: 8,
                                          ),
                                          padding: const EdgeInsets.all(12),
                                          decoration: BoxDecoration(
                                            color: Colors.grey[50],
                                            borderRadius: BorderRadius.circular(
                                              8,
                                            ),
                                            border: Border.all(
                                              color: Colors.grey[300]!,
                                            ),
                                          ),
                                          child: Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceBetween,
                                            children: [
                                              Column(
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.start,
                                                children: [
                                                  Text(
                                                    installment['stage'],
                                                    style: const TextStyle(
                                                      fontSize: 14,
                                                      fontWeight:
                                                          FontWeight.w500,
                                                    ),
                                                  ),
                                                  Text(
                                                    DateFormat(
                                                      'yyyy-MM-dd',
                                                    ).format(
                                                      DateTime.parse(
                                                        installment['date'],
                                                      ),
                                                    ),
                                                    style: TextStyle(
                                                      fontSize: 12,
                                                      color: Colors.grey[600],
                                                    ),
                                                  ),
                                                ],
                                              ),
                                              Text(
                                                '¥${oneStagesAmount.value.toStringAsFixed(2)}',
                                                style: TextStyle(
                                                  fontSize: 14,
                                                  fontWeight: FontWeight.bold,
                                                  color:
                                                      themeController
                                                          .themeColor,
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                      )
                                      .toList(),
                                ],
                              )
                              : const SizedBox.shrink(),
                    ),
                    const SizedBox(height: 16),

                    // 4. 分类选择标题和添加按钮
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          '分类',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            color: themeController.themeColor,
                          ),
                        ),
                        IconButton(
                          onPressed: _showAddCategoryDialog,
                          icon: Icon(
                            Icons.add_circle_outline,
                            color: themeController.themeColor,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 16),

                    // 5. 分类选择网格
                    Obx(
                      () => GridView.builder(
                        shrinkWrap: true,
                        physics: const NeverScrollableScrollPhysics(),
                        gridDelegate:
                            const SliverGridDelegateWithFixedCrossAxisCount(
                              crossAxisCount: 4,
                              childAspectRatio: 1,
                              crossAxisSpacing: 16,
                              mainAxisSpacing: 16,
                            ),
                        itemCount: categoryController.categories.length,
                        itemBuilder: (context, index) {
                          final category = categoryController.categories[index];
                          final isSelected =
                              selectedCategory == category['name'];
                          return InkWell(
                            onTap: () {
                              setState(() {
                                selectedCategory = category['name'];
                              });
                            },
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Container(
                                  padding: const EdgeInsets.all(12),
                                  decoration: BoxDecoration(
                                    color:
                                        isSelected
                                            ? themeController.themeColor
                                                .withOpacity(0.1)
                                            : Colors.grey[50],
                                    shape: BoxShape.circle,
                                    border: Border.all(
                                      color:
                                          isSelected
                                              ? themeController.themeColor
                                              : Colors.transparent,
                                      width: 2,
                                    ),
                                  ),
                                  child: Icon(
                                    category['icon'] as IconData,
                                    color:
                                        isSelected
                                            ? themeController.themeColor
                                            : Colors.grey,
                                    size: 24,
                                  ),
                                ),
                                const SizedBox(height: 8),
                                Text(
                                  category['name'],
                                  style: TextStyle(
                                    color:
                                        isSelected
                                            ? themeController.themeColor
                                            : Colors.grey,
                                    fontSize: 12,
                                    fontWeight:
                                        isSelected
                                            ? FontWeight.bold
                                            : FontWeight.normal,
                                  ),
                                ),
                              ],
                            ),
                          );
                        },
                      ),
                    ),
                    const SizedBox(height: 24),

                    // 6. 备注输入框
                    Container(
                      decoration: BoxDecoration(
                        color: Colors.grey[50],
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: TextField(
                        controller: noteController,
                        decoration: const InputDecoration(
                          hintText: '添加备注...',
                          border: InputBorder.none,
                          contentPadding: EdgeInsets.all(16),
                        ),
                      ),
                    ),
                    const SizedBox(height: 100), // 为底部按钮留出空间
                  ],
                ),
              ),
            ),
            // 浮动保存按钮
            Positioned(
              left: 16,
              right: 16,
              bottom: 16,
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.1),
                      blurRadius: 10,
                      offset: const Offset(0, -2),
                    ),
                  ],
                ),
                child: ElevatedButton(
                  onPressed: changeAmount,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: themeController.themeColor,
                    padding: const EdgeInsets.symmetric(vertical: 16),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                    elevation: 0,
                  ),
                  child: const Text(
                    '保存',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget reFund() {
    final TextEditingController _refundController = TextEditingController(
      text: countController.reFund?.toString() ?? '',
    );
    return Container(
      width: double.infinity,
      height: 50,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Row(
            children: [
              // 美化后的按钮
              ElevatedButton.icon(
                icon: Icon(Icons.savings, color: Colors.white),
                label: Text('回本设置', style: TextStyle(fontSize: 12,color: Colors.white)),
                style: ElevatedButton.styleFrom(
                  backgroundColor: themeController.themeColor,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(24),
                  ),
                  elevation: 4,
                  padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                ),
                onPressed: () {
                  showDialog(
                    context: context,
                    builder:
                        (_) => AlertDialog(
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(20),
                          ),
                          title: Row(
                            children: [
                              Icon(
                                Icons.savings,
                                color: themeController.themeColor,
                              ),
                              SizedBox(width: 8),
                              Text('设置每日回本金额'),
                            ],
                          ),
                          content: TextField(
                            controller: _refundController,
                            keyboardType: TextInputType.numberWithOptions(
                              decimal: true,
                            ),
                            decoration: InputDecoration(
                              prefixText: '¥ ',
                              hintText: '请输入金额',
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(12),
                              ),
                            ),
                          ),
                          actions: [
                            TextButton(
                              child: Text('取消'),
                              onPressed: () => Navigator.pop(context),
                            ),
                            ElevatedButton(
                              child: Text('确定'),
                              style: ElevatedButton.styleFrom(
                                backgroundColor: themeController.themeColor,
                              ),
                              onPressed: () {
                                setState(() {
                                  countController.reFund =
                                      _refundController.text;
                                });
                                Navigator.pop(context);
                              },
                            ),
                          ],
                        ),
                  );
                },
              ),
              SizedBox(width: 3),
              // 美化后的每日回本金额显示
              Card(
                elevation: 2,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(16),
                ),
                child: Padding(
                  padding: EdgeInsets.symmetric(horizontal: 17, vertical: 7),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Icon(
                        Icons.attach_money,
                        color: themeController.themeColor,
                      ),
                      SizedBox(width: 8),
                      Text(
                        "每日回本金额：",
                        style: TextStyle(fontSize: 16, color: Colors.grey[700]),
                      ),
                      Text(
                        "¥${countController.reFund ?? ''}",
                        style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                          color: themeController.themeColor,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildTypeButton(String type, bool isSelected) {
    return InkWell(
      onTap: () {
        setState(() {
          selectedType = type;
        });
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
        decoration: BoxDecoration(
          color: isSelected ? themeController.themeColor : Colors.grey[50],
          borderRadius: BorderRadius.circular(20),
          border: Border.all(
            color: isSelected ? themeController.themeColor : Colors.grey[300]!,
            width: 1,
          ),
        ),
        child: Text(
          type,
          style: TextStyle(
            color: isSelected ? Colors.white : Colors.grey[600],
            fontSize: 16,
            fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
          ),
        ),
      ),
    );
  }

  Future<void> _selectFirstPaymentDate() async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: firstPaymentDate.value,
      firstDate: DateTime.now(),
      lastDate: DateTime.now().add(const Duration(days: 365)),
      builder: (context, child) {
        return Theme(
          data: Theme.of(context).copyWith(
            colorScheme: ColorScheme.light(
              primary: themeController.themeColor,
              onPrimary: Colors.white,
              surface: Colors.white,
              onSurface: Colors.black,
            ),
          ),
          child: child!,
        );
      },
    );
    if (picked != null && picked != firstPaymentDate.value) {
      firstPaymentDate.value = picked;
    }
  }

  Future<void> _selectTransactionDate() async {
    final DateTime? pickedDate = await showDatePicker(
      context: context,
      initialDate: transactionDate.value,
      firstDate: DateTime(2000),
      lastDate: DateTime(2100),
      builder: (context, child) {
        return Theme(
          data: Theme.of(context).copyWith(
            colorScheme: ColorScheme.light(
              primary: themeController.themeColor,
              onPrimary: Colors.white,
              surface: Colors.white,
              onSurface: Colors.black,
            ),
          ),
          child: child!,
        );
      },
    );

    if (pickedDate != null) {
      final TimeOfDay? pickedTime = await showTimePicker(
        context: context,
        initialTime: TimeOfDay.fromDateTime(transactionDate.value),
        builder: (context, child) {
          return Theme(
            data: Theme.of(context).copyWith(
              colorScheme: ColorScheme.light(
                primary: themeController.themeColor,
                onPrimary: Colors.white,
                surface: Colors.white,
                onSurface: Colors.black,
              ),
            ),
            child: child!,
          );
        },
      );

      if (pickedTime != null) {
        final DateTime newDateTime = DateTime(
          pickedDate.year,
          pickedDate.month,
          pickedDate.day,
          pickedTime.hour,
          pickedTime.minute,
        );
        setState(() {
          transactionDate.value = newDateTime;
        });
      }
    }
  }
}
